home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 February: Tool Chest / Apple Developer CD Series Tool Chest February 1996 (Apple Computer)(1996).iso / Tool Chest / Development Tools & Languages / • Other Platforms / PCCTS 1.31 / h / List.C < prev    next >
Encoding:
C/C++ Source or Header  |  1995-03-10  |  1.3 KB  |  74 lines  |  [TEXT/MPS ]

  1. #include "List.h"
  2.  
  3. /* Iterate over a list of elements; returns ptr to a new element
  4.  * in list upon every call and NULL when no more are left.
  5.  * Very useful like this:
  6.  *
  7.  *        cursor = mylist;
  8.  *        while ( (p=mylist->iterate(&cursor)) ) {
  9.  *            // place with element p
  10.  *        }
  11.  *
  12.  * The cursor must be initialized to point to the list to iterate over.
  13.  */
  14. void *List::
  15. iterate(ListNode **cursor)
  16. {
  17.     void *e;
  18.  
  19.     if ( cursor == NULL || *cursor==NULL ) return NULL;
  20.     if ( head == *cursor ) { *cursor = (*cursor)->next(); }
  21.     e = (*cursor)->elem();
  22.     (*cursor) = (*cursor)->next();
  23.     return e;
  24. }
  25.  
  26. /* add an element to end of list. */
  27. void List::
  28. add(void *e)
  29. {
  30.     ListNode *p, *tail;
  31.     require(e!=NULL, "slist_add: attempting to add NULL list element");
  32.  
  33.     p = new ListNode;
  34.     require(p!=NULL, "add: cannot alloc new list node");
  35.     p->setElem(e);
  36.     if ( head == NULL )
  37.     {
  38.         head = tail = p;
  39.     }
  40.     else                                /* find end of list */
  41.     {
  42.         tail->setNext(p);
  43.         tail = p;
  44.     }
  45. }
  46.  
  47. void List::
  48. lfree()
  49. {
  50.     ListNode *p,*q;
  51.  
  52.     if ( head==NULL ) return;    /* empty list */
  53.     for (p = head; p!=NULL; p=q)
  54.     {
  55.         q = p->next();
  56.         free(p);
  57.     }
  58. }
  59.  
  60. PCCTS_AST *List::
  61. to_ast(List list)
  62. {
  63.     PCCTS_AST *t=NULL, *last=NULL;
  64.     ListNode *p;
  65.  
  66.     for (p = head; p!=NULL; p=p->next())
  67.     {
  68.         PCCTS_AST *u = (PCCTS_AST *)p->elem;
  69.         if ( last==NULL ) last = t = u;
  70.         else { last->setRight(u); last = u; }
  71.     }
  72.     return t;
  73. }
  74.